package com.example.yichuangyun.mvvm.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentSearchCompanyBinding;
import com.example.yichuangyun.dialog.AreaScreenPopupWindow;
import com.example.yichuangyun.dialog.ContactsCompanyDialog;
import com.example.yichuangyun.dialog.ManagementStatusScreenPopupWindow;
import com.example.yichuangyun.dialog.MoreScreenPopupWindow;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.company.AreaModel;
import com.example.yichuangyun.model.company.CompanyDataModel;
import com.example.yichuangyun.model.company.CompanyDetailsContactsDataModel;
import com.example.yichuangyun.model.company.CompanyListParamsModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.CompanyDetailsActivity;
import com.example.yichuangyun.mvvm.ui.activity.MapSearchActivity;
import com.example.yichuangyun.mvvm.ui.activity.SearchCompanyActivity;
import com.example.yichuangyun.mvvm.ui.adapter.SearchCompanyAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.view.SearchCompanyViewModel;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.ToastHelper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜企业
 */
public class SearchCompanyFragment extends BaseFragment<FragmentSearchCompanyBinding, SearchCompanyViewModel> {

    private ActivityResultLauncher<Intent> searchLauncher;
    private int page = 1;
    private SearchCompanyAdapter adapter;
    private AreaScreenPopupWindow areaPopupWindow;
    private ManagementStatusScreenPopupWindow managementStatusScreenPopupWindow;
    private MoreScreenPopupWindow moreScreenPopupWindow;

    /**
     * 区域id集合
     */
    private List<String> mRegAddressIds = new ArrayList<>();
    /**
     * 经营状态code集合
     */
    private List<Integer> mStatusCode = new ArrayList<>();
    /**
     * 区域内容
     */
    private String areaName;
    /**
     * 经营状态内容
     */
    private String managementStatus;

    private CompanyListParamsModel mCompanyListParamsModel = new CompanyListParamsModel();

    private CompanyDataModel.CompanyModel mCompanyModel;
    private int mPosition;

    /**
     * 声明AMapLocationClient类对象
     */
    private AMapLocationClient mLocationClient = null;

    private AMapLocationClientOption mLocationOption;

    private String latitude, longitude;
    private String mDistance = null;

    private boolean isFirstLocation = true;

    @Override
    protected SearchCompanyViewModel bindModel() {
        return getViewModel(this, SearchCompanyViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        adapter = new SearchCompanyAdapter(mContext);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(mContext, R.layout.loading_view);
        binding.setMSearchCompanyViewModel(viewModel);
        initPopWindow();
        searchLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                if (result.getData() != null) {
                    binding.ivClear.setVisibility(View.VISIBLE);
                    binding.tvSearchContent.setText(result.getData().getStringExtra(Constant.keywordsKey));
                    page = 1;
                    binding.recyclerView.scrollToPosition(0);
                    binding.smartRefreshLayout.autoRefresh();
                }
            }
        });
    }

    @Override
    public void lazyLoadData() {
        viewModel.getAreaList();
        initLocation();
    }

    /**
     * 企业列表请求
     */
    private void getCompanyList(int page) {
        mCompanyListParamsModel.setKeywords(binding.tvSearchContent.getText().toString());
        mCompanyListParamsModel.setPage(page);
        mCompanyListParamsModel.setPageSize(Constant.pageSize);
        mCompanyListParamsModel.setRegAddressIds(mRegAddressIds); // 注册地址
        mCompanyListParamsModel.setStatusList(mStatusCode); // 经营状态
        if (latitude != null && longitude != null && mDistance != null && mRegAddressIds.size() == 0) {
            mCompanyListParamsModel.setDistance(mDistance); // 距离
            mCompanyListParamsModel.setGdLatitude(latitude); // 纬度
            mCompanyListParamsModel.setGdLongitude(longitude); // 经度
        } else {
            mCompanyListParamsModel.setDistance(null); // 距离
            mCompanyListParamsModel.setGdLatitude(null); // 纬度
            mCompanyListParamsModel.setGdLongitude(null); // 经度
        }
        viewModel.getCompanyList(mCompanyListParamsModel);
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.ivMap, o -> JumpIntent.jump(getActivity(), MapSearchActivity.class));
        // 所有区域
        viewModel.onDelayClick(binding.llAllArea, o -> {
            if (areaPopupWindow != null) {
                binding.tvAllAreaText.setTextColor(0xFF426FFF);
                binding.ivAllArea.setImageResource(R.mipmap.icon_up_blue);
                areaPopupWindow.showAsDropDown(binding.line);
            }
        });

        // 经营状态
        viewModel.onDelayClick(binding.llManagementStatus, o -> {
            binding.tvManagementStatusText.setTextColor(0xFF426FFF);
            binding.ivManagementStatus.setImageResource(R.mipmap.icon_up_blue);
            managementStatusScreenPopupWindow.showAsDropDown(binding.line);
        });

        // 更多筛选
        viewModel.onDelayClick(binding.llMoreScreen, o -> {
            binding.tvMoreScreenText.setTextColor(0xFF426FFF);
            binding.ivMoreScreen.setImageResource(R.mipmap.icon_more_sel);
            moreScreenPopupWindow.showAsDropDown(binding.line);
        });

        // 收藏
        adapter.addOnItemChildClickListener(R.id.ll_like, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            // 0未收藏、1已收藏
            if (null != mCompanyModel) {
                if (mCompanyModel.getCollectState() == 0) {
                    viewModel.collectCompany(mCompanyModel);
                } else {
                    viewModel.cancelCollectCompany(mCompanyModel.getEid());
                }
            }
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getCompanyList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getCompanyList(page);
            }
        });

        // 区域返回结果
        viewModel.areaList.observe(this, this::initAreaPopWindow);

        // 企业列表返回结果
        viewModel.companyDataModelMutableLiveData.observe(this, companyDataModel -> {
            adapter.setKeywords(binding.tvSearchContent.getText().toString());
            binding.tvCompanyCount.setText(Html.fromHtml(mContext.getString(R.string.find_company_count, companyDataModel.getTotalSize()), Html.FROM_HTML_MODE_LEGACY));
            List<CompanyDataModel.CompanyModel> list = companyDataModel.getData();
            if (null != list) {
                if (list.size() < Constant.pageSize) {
                    binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                }
                if (page == 1) {
                    if (list.isEmpty()) {
                        adapter.setEmptyViewLayout(mContext, R.layout.layout_empty_list);
                    }
                    adapter.submitList(list);
                    binding.smartRefreshLayout.finishRefresh();
                } else {
                    adapter.addAll(list);
                    binding.smartRefreshLayout.finishLoadMore();
                }
            } else {
                adapter.setEmptyViewLayout(mContext, R.layout.layout_empty_list);
            }
        });

        // 列表返回错误结果
        viewModel.getListErrorMutableLiveData.observe(this, s -> {
            binding.smartRefreshLayout.finishRefresh();
            binding.smartRefreshLayout.finishLoadMore();
        });

        // 收藏成功返回结果
        viewModel.collectSuccessMutableLiveData.observe(this, s -> {
            mCompanyModel.setCollectState(1);
            adapter.notifyItemChanged(mPosition, "1");
            ToastHelper.show(getString(R.string.collect_success));
        });

        // 取消收藏返回结果
        viewModel.cancelCollectSuccessMutableLiveData.observe(this, s -> {
            mCompanyModel.setCollectState(0);
            adapter.notifyItemChanged(mPosition, "1");
            ToastHelper.show(getString(R.string.cancel_collect_success));
        });

        adapter.addOnItemChildClickListener(R.id.ll_call, (baseQuickAdapter, view, i) -> {
            CompanyDataModel.CompanyModel companyModel = baseQuickAdapter.getItem(i);
            if (null != companyModel) {
                viewModel.getContacts(companyModel.getEid());
            }
        });

        // 可拨打电话返回结果
        viewModel.contactsMutableLiveData.observe(this, contactsModels -> {
            if (null != contactsModels && contactsModels.size() > 0) {
                initDialog(contactsModels);
            } else {
                ToastHelper.show(mContext.getString(R.string.no_contact_phone));
            }
        });

        // 清除搜索内容
        viewModel.onDelayClick(binding.ivClear, o -> {
            binding.ivClear.setVisibility(View.GONE);
            binding.tvSearchContent.setText("");
            page = 1;
            binding.recyclerView.scrollToPosition(0);
            binding.smartRefreshLayout.autoRefresh();
        });

        // 搜索
        binding.tvSearchContent.setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), SearchCompanyActivity.class);
            intent.putExtra(Constant.keywordsKey, binding.tvSearchContent.getText().toString());
            searchLauncher.launch(intent);
        });

        adapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.fromKey, 1);
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(getActivity(), CompanyDetailsActivity.class, bundle);
        });

        adapter.addOnItemChildClickListener(R.id.tv_reg_address, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.fromKey, 1);
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(getActivity(), CompanyDetailsActivity.class, bundle);
        });
        adapter.addOnItemChildClickListener(R.id.tv_report_address, (baseQuickAdapter, view, i) -> {
            mCompanyModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.fromKey, 1);
            bundle.putString(Constant.eidKey, mCompanyModel.getEid());
            bundle.putString(Constant.reportAddressKey, mCompanyModel.getReportAddress());
            JumpIntent.jump(getActivity(), CompanyDetailsActivity.class, bundle);
        });
    }

    private void initAreaPopWindow(List<AreaModel> areaList) {
        // 区域弹窗
        areaPopupWindow = new AreaScreenPopupWindow(mContext, areaList) {
            @Override
            public void confirm(List<String> regAddressIds, String area, String distance) {
                mDistance = distance;
                mRegAddressIds = regAddressIds;
                areaName = area;
                page = 1;
                binding.recyclerView.scrollToPosition(0);
                binding.smartRefreshLayout.autoRefresh();
            }
        };
        areaPopupWindow.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(areaName)) {
                binding.tvAllAreaText.setText(areaName);
                binding.tvAllAreaText.setTextColor(0xFF426FFF);
                binding.ivAllArea.setImageResource(R.mipmap.icon_down_blue);
            } else {
                binding.tvAllAreaText.setText(mContext.getString(R.string.all));
                binding.tvAllAreaText.setTextColor(0xFF4A4A4A);
                binding.ivAllArea.setImageResource(R.mipmap.icon_down2);
            }
        });
    }

    private void initPopWindow() {
        // 经营状态弹窗
        managementStatusScreenPopupWindow = new ManagementStatusScreenPopupWindow(mContext) {
            @Override
            public void confirm(List<Integer> statusCode, String status) {
                managementStatus = status;
                mStatusCode = statusCode;
                page = 1;
                binding.recyclerView.scrollToPosition(0);
                binding.smartRefreshLayout.autoRefresh();
            }
        };
        managementStatusScreenPopupWindow.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(managementStatus)) {
                binding.tvManagementStatusText.setText(managementStatus);
                binding.tvManagementStatusText.setTextColor(0xFF426FFF);
                binding.ivManagementStatus.setImageResource(R.mipmap.icon_down_blue);
            } else {
                binding.tvManagementStatusText.setText(mContext.getString(R.string.management_status));
                binding.tvManagementStatusText.setTextColor(0xFF4A4A4A);
                binding.ivManagementStatus.setImageResource(R.mipmap.icon_down2);
            }
        });

        // 更多筛选弹窗
        moreScreenPopupWindow = new MoreScreenPopupWindow(mContext) {
            @Override
            public void confirm(CompanyListParamsModel companyListParamsModel) {
                mCompanyListParamsModel = companyListParamsModel;
                page = 1;
                binding.recyclerView.scrollToPosition(0);
                binding.smartRefreshLayout.autoRefresh();
            }
        };
        moreScreenPopupWindow.setOnDismissListener(() -> {
            binding.tvMoreScreenText.setTextColor(0xFF4A4A4A);
            binding.ivMoreScreen.setImageResource(R.mipmap.icon_more_def);
        });
    }

    private void initDialog(List<CompanyDetailsContactsDataModel.ContactsModel> contactsData) {
        ContactsCompanyDialog contactsCompanyDialog = new ContactsCompanyDialog(mContext, contactsData, 4);
        contactsCompanyDialog.showDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshCompanyList)) {
                mCompanyModel.setCollectState(eventBusModel.getStatus());
                adapter.notifyItemChanged(mPosition, "1");
            }
        }
    }

    public void initLocation() {
        // 声明定位回调监听器
        AMapLocationListener mLocationListener = aMapLocation -> {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //可在其中解析aMapLocation获取相应内容。
                    latitude = String.valueOf(aMapLocation.getLatitude()); // 获取纬度
                    longitude = String.valueOf(aMapLocation.getLongitude()); // 获取经度
                    adapter.setLocation(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                    areaPopupWindow.setLocationStatus(mContext.getString(R.string.my_nearby_company));
                    if (isFirstLocation) {
                        isFirstLocation = false;
                        getCompanyList(page);
                    }
                    Log.e("@@@@@@@@定位成功", "纬度：" + aMapLocation.getLatitude() + "，经度：" + aMapLocation.getLongitude());
                } else {
//                    ToastHelper.showLong("请检查是否开启定位权限");
                    getCompanyList(page);
                    areaPopupWindow.setLocationStatus(mContext.getString(R.string.location_error));
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("aMapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            } else {
                getCompanyList(page);
                areaPopupWindow.setLocationStatus(mContext.getString(R.string.location_error));
            }
        };

        // 声明AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(10000);
        try {
            // 初始化定位
            mLocationClient = new AMapLocationClient(mContext);
            // 给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 设置定位回调监听
            mLocationClient.setLocationListener(mLocationListener);
            // 启动定位
            mLocationClient.startLocation();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        startLocation();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            // 停止定位
            mLocationClient.stopLocation();
        }
    }

    private void startLocation() {
        if (mLocationClient != null && mLocationOption != null) {
            //根据控件的选择，重新设置定位参数
            resetOption();
            // 设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 启动定位
            mLocationClient.startLocation();
        }
    }

    // 根据控件的选择，重新设置定位参数
    private void resetOption() {
        // 设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // 设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(10000);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mLocationClient != null) {
            if (isVisibleToUser) {
                mLocationClient.startLocation();
            } else {
                mLocationClient.stopLocation();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mLocationClient != null) {
            // 停止定位后，本地定位服务并不会被销毁
            mLocationClient.stopLocation();
            // 销毁定位客户端，同时销毁本地定位服务。
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }
}
